const Pager = require('../aotoo/core/index')
let lib = Pager.lib

const dropdownList = (data, parentId, type, ids) => {
  let output = []
  data.map(item => {
    output.push({
      title: {
        title: item.title
      },
      aim: 'onItem?parentId='+parentId+'&type='+type+'&id='+item.id,
      itemClass: `'item-rc nopd item-${type} ${ids && ids.indexOf(item.id) >=0 ? 'active' : ''}`
    })
  })
  return output
}
const footer = (parentId, type)=> {
  if (type === 'checkbox') {
    return {
      title: [
        {title: '重置', itemClass: 'ss-button btn-grey plain', aim: 'onReset'},
        {title: '确认', itemClass: 'ss-button btn-default', aim: 'onSure?parentId='+parentId}
      ],
      titleClass: 'btn-footer wrap'
    }
  }
}

module.exports = function mkDropdown(params) {
  let dft = {
    id: lib.suid('dd-list-'),
    listClass: '',
    data: [],
    type: 'radio',
    parentId: '' ,        //用来标注是第几个的list
    ids: '',            //选中值
  }

  let opts = Object.assign({}, dft, params)
  let data = dropdownList(opts.data, opts.parentId, opts.type, opts.ids)
  return {
    $$id: opts.$$id || opts.id,
    listClass: opts.listClass,
    data: data,
    footer: footer(opts.parentId, opts.type),
    methods: {
      updatex(params) {
        if (typeof params === "object" && params.length > 0) {
          params = dropdownList(params, opts.parentId, opts.type, params.id)
        }
        else {
          params.data = dropdownList(params.data, opts.parentId, opts.type, params.id)
        }
        this.update(params)
      },
      onSure(e, params, inst) {
        //多选 确认按钮
        const _parentId = params.parentId
        let _output = ''
        this.getData().data.forEach(item => {
          if (item.itemClass.indexOf('active') > -1) {
            _output += _output ? (',' +item.title.title) : item.title.title
          }
        })
        this.hooks.emit('keep-val', {vals: _output, parentId: _parentId})
      },
      onReset(e, params, inst) {
        //重置按钮
        const dt = dropdownList(opts.data, opts.parentId, opts.type)
        this.update(dt)
      },
      onItem(e, params, inst) {
        const type = params.type
        const _parentId = params.parentId
        if (type === 'radio') {
          inst.siblings().removeClass('active')
          inst.addClass('active')
          this.hooks.emit('dropdownlist-radio', {vals: inst.getData().title.title, parentId: _parentId})
        }
        else {
          inst.toggleClass('active')
        }
      },
    }
  }
}